package com.jz.community.modulemine.money.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextWatcher;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.gyf.barlibrary.ImmersionBar;
import com.jakewharton.rxbinding2.view.RxView;
import com.jz.community.basecomm.base.BaseMvpActivity;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.RxDataTool;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.modulemine.R;
import com.jz.community.modulemine.R2;
import com.jz.community.modulemine.money.bean.MoneyExchangeCodeBean;
import com.jz.community.modulemine.money.presenter.MoneyExchangePresenter;
import com.qmuiteam.qmui.util.QMUIKeyboardHelper;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

@Route(path = RouterIntentConstant.MONEY_EXCHANGE)
public class MoneyExchangeActivity extends BaseMvpActivity<MoneyExchangeView.View, MoneyExchangePresenter> implements MoneyExchangeView.View {

    @BindView(R2.id.exchange_back)
    ImageView exchangeBack;
    @BindView(R2.id.exchange_title)
    TextView exchangeTitle;
    @BindView(R2.id.exchange_toolbar)
    Toolbar exchangeToolbar;
    @BindView(R2.id.exchange_money_pb)
    ProgressBar exchangeMoneyPb;
    @BindView(R2.id.exchange_money_tv)
    TextView exchangeMoneyTv;
    @BindView(R2.id.exchange_money_rl)
    RelativeLayout exchangeMoneyRl;
    @BindView(R2.id.exchange_money_parent)
    RelativeLayout exchangeMoneyParent;
    @BindView(R2.id.exchange_edit)
    EditText exchangeEdit;
    @BindView(R2.id.exchange_edit_delete)
    ImageView exchangeEditDelete;
    @BindView(R2.id.exchange_edit_tips)
    TextView exchangeEditTips;
    @BindView(R2.id.exchange_edit_tips_ll)
    LinearLayout exchangeEditTipsLl;
    @BindView(R2.id.exchange_enter)
    TextView exchangeEnter;
    @BindView(R2.id.exchange_parent)
    RelativeLayout exchangeParent;

    //延时器
    private Disposable disposable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.module_mine_activity_money_exchange;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected MoneyExchangePresenter createPresenter() {
        return new MoneyExchangePresenter(this);
    }

    @Override
    protected void initView() {
        super.initView();
        ImmersionBar.with(this)
                .titleBar(exchangeToolbar)
                .statusBarDarkFont(true, 0.2f)//当白色背景状态栏遇到不能改变状态栏字体为深色的设备时，解决方案
                .init();

        exchangeTitle.setText("E卡兑换");

    }

    @SuppressLint("CheckResult")
    @Override
    protected void initDatas() {
        super.initDatas();
        SpannableString ss = new SpannableString("兑换码不区分大小写");
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(14, true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        exchangeEdit.setHint(new SpannedString(ss));

        exchangeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    exchangeEditDelete.setVisibility(View.VISIBLE);

                    exchangeEditTipsLl.setVisibility(View.GONE);
                } else {
                    exchangeEditDelete.setVisibility(View.GONE);

                    exchangeMoneyRl.setVisibility(View.GONE);
                    exchangeMoneyPb.setVisibility(View.GONE);
                    exchangeMoneyTv.setVisibility(View.GONE);

                    exchangeEditTipsLl.setVisibility(View.VISIBLE);
                    exchangeEditTips.setText("请输入E卡兑换码!");

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                //走接口
                if (s.length() == 12) {
                    initCodeInfo();
                }

            }
        });


        RxView.clicks(exchangeEnter)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    String code = exchangeEdit.getText().toString().trim();
                    if (!RxDataTool.isNullString(code)) {
                        //不为空
                        if (code.length() < 12) {
                            //小于11位
                            exchangeEditTipsLl.setVisibility(View.VISIBLE);
                            exchangeEditTips.setText("请输入正确的E卡兑换码");
                        } else {
                            exchangeMoney(code);
                        }


                    }
                });
    }

    private void initCodeInfo() {
        disposable = Observable.just("1")
                .delay(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    //执行查询接口
                    exchangeMoneyRl.setVisibility(View.VISIBLE);
                    exchangeMoneyPb.setVisibility(View.VISIBLE);

                    String code = exchangeEdit.getText().toString().trim();
                    mPresenter.initExchangeInfo(code);

                });
    }

    private void exchangeMoney(String code) {
        showLoading();
        mPresenter.exchangeMoney(code);

    }

    @Override
    public void getCodeSuccess(MoneyExchangeCodeBean entity) {
        if (!RxDataTool.isNullString(entity.getPrice())) {
            exchangeMoneyRl.setVisibility(View.VISIBLE);
            exchangeMoneyPb.setVisibility(View.GONE);
            exchangeMoneyTv.setVisibility(View.VISIBLE);
            exchangeMoneyTv.setText("面值" + entity.getPrice() + "元");
        } else {
            exchangeMoneyRl.setVisibility(View.GONE);
            exchangeMoneyPb.setVisibility(View.GONE);
            exchangeMoneyTv.setVisibility(View.GONE);
        }

    }

    @Override
    public void exchangeSuccess() {
        dismissLoading();
        showNormal("兑换成功!");
        EventBus.getDefault().post(new AppEvent(EventConfig.REFRESH_MONEY_DETAIL));
        finish();

    }

    @Override
    public void getCodeFail(String msg) {
        exchangeMoneyRl.setVisibility(View.GONE);
        exchangeMoneyPb.setVisibility(View.GONE);
        exchangeMoneyTv.setVisibility(View.GONE);

    }

    @Override
    public void exchangeFail(int code, String msg) {
        dismissLoading();
        exchangeEditTipsLl.setVisibility(View.VISIBLE);
        if (code == 404) {
            exchangeEditTips.setText("兑换码错误");
        } else if (code == 409) {
            exchangeEditTips.setText("兑换码已兑换");
        } else {
            exchangeEditTipsLl.setVisibility(View.GONE);
            showNormal("兑换失败");
        }


    }

    private void dispose() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dispose();
    }

    @OnClick(R2.id.exchange_back)
    public void backClick(View view) {
        QMUIKeyboardHelper.hideKeyboard(exchangeEdit);
        finish();
    }

    @OnClick(R2.id.exchange_edit_delete)
    public void delClick(View view) {
        exchangeEdit.setText("");
    }

}
